﻿using System;
using System.Data;
using System.Web.UI.WebControls;
using CH.FourBoards.LagerWalti.WebFrontEnd.View.Master;

namespace CH.FourBoards.LagerWalti.WebFrontEnd.View.Generic.RecordSetView
{
    abstract public class RecordSetBase : PageBase
    {
        protected Repeater MenuRepeater;
        protected Repeater RecordSetRepeater;
        protected abstract DataTable CreateRecordSetSource();

        protected virtual DataTable CreateMenuSource()
        {
            return null;
        }

        protected virtual void OnTableRowCreated(RepeaterItem repeaterItem, DataRowView row)
        {
        }

        public string CreateMenuLink(string param, string value)
        {
            var query = string.Format("?{0}={1}", param, value);
            return CreateLink() + query;
        }

        

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            IncludeCss(GetPageBaseByNamespace(typeof(RecordSetBase)) + "record-list.css");
            IncludeScript(GetPageBaseByNamespace(typeof(RecordSetBase)) + "record-list.js");

            try {
                LoadRecordSet();
                LoadMenu();
            } catch (Exception ex) {
                ShowException(ex);
            }
        }

        private void LoadRecordSet()
        {
            RecordSetRepeater.ItemDataBound += RecordSetRepeater_ItemDataBound;
            RecordSetRepeater.DataSource = CreateRecordSetSource();
            RecordSetRepeater.DataBind();
        }

        private void RecordSetRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            // check item type
            var item = e.Item;
            if (!(item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)) {
                return;
            }

            // get row
            var row = (DataRowView) item.DataItem;
            OnTableRowCreated(item, row);
        }

        private void LoadMenu()
        {
            if (MenuRepeater == null) {
                return;
            }
            MenuRepeater.DataSource = CreateMenuSource();
            MenuRepeater.DataBind();
        }

    }
}